import { useEffect, lazy, Suspense, useContext } from 'react';
import { useLocation, useNavigate, useRoutes, type RouteObject } from 'react-router-dom';
import { Spin } from 'antd';
import nprogress from 'nprogress';
import 'nprogress/nprogress.css';
import Login from './pages/login';
import Main from './pages/main';
import MenuContext from './context/MenuContext';

nprogress.configure({ showSpinner: false });

const Loading = () => {
  useEffect(() => {
    nprogress.start();
    return () => nprogress.done();
  }, []);
  return <Spin />;
};

const Routes = () => {
  const { pathname } = useLocation();
  const navigate = useNavigate();
  const { menu } = useContext(MenuContext)!;

  const token = sessionStorage.getItem('token');
  const authRoutes: AnyObject[] = menu.filter((item: AnyObject) => item.url);

  useEffect(() => {
    // 如果用户访问非登录页，并且没有token，那就跳回登录页
    if (pathname !== '/' && !token) navigate('/');
  });

  const lazyLoad = (name: string) => {
    const Component = lazy(() => import(`./pages/${name}/index.tsx`));
    return <Suspense fallback={<Loading />}>
      <Component />
    </Suspense>;
  };

  // 未登录只注册登录页
  const routes: RouteObject[] = [{
    path: '/',
    element: <Login />
  }];

  if (token) {
    routes.push({
      path: '/main',
      element: <Main />,
      children: [{
        path: 'home',
        element: lazyLoad('home')
      }, ...authRoutes.map(({ url }) => ({
        path: url.slice(1),
        element: lazyLoad(url.slice(1))
      }))]
    }, {
      path: '*',
      element: <p>404</p>
    })
  }

  const element = useRoutes(routes);
  return element;
};

export default Routes;
